package cn.net.isir.controller.manager;

import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.entity.Organizations;
import cn.net.isir.entity.TimeRange;
import cn.net.isir.entity.UserOrg;
import cn.net.isir.entity.UserValidInfo;
import cn.net.isir.service.*;
import cn.net.isir.service2.TotalFlowStatisticsService;
import cn.net.isir.utils.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author liuxubo
 * @filename TotalFlowStatisticsController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2019/03/08
 * @comment
 * @since 1.8
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/amountstatistics")
public class TotalFlowStatisticsController {
    @Resource
    private UserValidInfoService userValidInfoService;
    @Resource
    private UserOrgService userOrgService;
    @Resource
    private OrganizationsService organizationsService;
    @Resource
    private TotalFlowStatisticsService totalFlowStatisticsService;
    @Resource
    private CRMUserManagerService crmUserManagerService;

    /**
     * 获取四个统计信息（本日，本月，本季度，本年）
     *
     * @param ids 组织机构id
     * @return 四个统计信息
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ResultObject getInfo(String ids) {
        BigDecimal day = BigDecimal.ZERO;
        BigDecimal month = BigDecimal.ZERO;
        BigDecimal quarter = BigDecimal.ZERO;
        BigDecimal year = BigDecimal.ZERO;

        //获取到当前组织机构下所有的子组织机构的人员（不包含本组织机构的人员）
        Set<String> userSet = getSalesmanIdByOrgId(ids);
        //获取到当前组织机构下所有的人员（不包含子组织机构的人员），当ids为空时只能获取到自己
        Set<String> nowIds = getSelfSalemanIdByOrgId(ids);
        // 查询所有子组织机构的人员店铺营业额
        for (String s : userSet) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s, crmUserManagerService.getTimeRangeList(s));
            Map<String, BigDecimal> result1 = totalFlowStatisticsService.getTotalStatistics(salesman, crmUserManagerService.getTurnedShopIds());
            if (!result1.isEmpty()) {
                if (result1.get("day") != null) {
                    day = day.add(result1.get("day"));
                }
                if (result1.get("month") != null) {
                    month = month.add(result1.get("month"));
                }
                if (result1.get("quarter") != null) {
                    quarter = quarter.add(result1.get("quarter"));
                }
                if (result1.get("year") != null) {
                    year = year.add(result1.get("year"));
                }
            }
        }
        // 查询当前登录用户营业额（只有自己，没有同级用户）
        for (String s1 : nowIds) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s1, crmUserManagerService.getTimeRangeList(s1));
            Map<String, BigDecimal> result2 = totalFlowStatisticsService.getTotalStatistics(salesman, crmUserManagerService.getTurnedShopIds());
            if (!result2.isEmpty()) {
                if (result2.get("day") != null) {
                    day = day.add(result2.get("day"));
                }
                if (result2.get("month") != null) {
                    month = month.add(result2.get("month"));
                }
                if (result2.get("quarter") != null) {
                    quarter = quarter.add(result2.get("quarter"));
                }
                if (result2.get("year") != null) {
                    year = year.add(result2.get("year"));
                }
            }
        }
        Map<String, BigDecimal> result = new HashMap<>();
        result.put("day", day);
        result.put("month", month);
        result.put("quarter", quarter);
        result.put("year", year);
        return new ResultObject(200, "success", result);
    }

    /**
     * 获取四个统计信息（本日，本月，本季度，本年）
     *
     * @param ids 组织机构id
     * @return 四个统计信息
     */
    @RequestMapping(value = "/chart", method = RequestMethod.GET)
    public ResultObject getChars(String ids) {
        //每日
        Set<String> userSet = getSalesmanIdByOrgId(ids);
        //当ids为空的时候，说明没有选择组织机构，所以只显示自己的总营业额信息
        if (StringUtils.isBlank(ids)) {
            userSet.add(TokenManager.getTokenId());
        }
        if (!StringUtils.isBlank(ids)) {
            Set<String> nowIds = getSelfSalemanIdByOrgId(ids);
            userSet.addAll(nowIds);
        }
        Map<String, BigDecimal> daysResult = new LinkedHashMap<>();
        // 所有人
        for (String s : userSet) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s, crmUserManagerService.getTimeRangeList(s));
            Map<String, BigDecimal> result = totalFlowStatisticsService.getDaysFlowAtMonth(salesman, crmUserManagerService.getTurnedShopIds());
            result.forEach((key, value) -> {
                // 判断是否已经有此日的数据了
                BigDecimal b = daysResult.get(key);
                // 没有则新增
                if (b == null) daysResult.put(key, value);
                else {// 有,则在原基础上增加
                    daysResult.put(key, b.add(value));
                }
            });
        }

        Map<String, BigDecimal> monthsResult = new LinkedHashMap<>();
        // 所有人
        for (String s : userSet) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s, crmUserManagerService.getTimeRangeList(s));
            Map<String, BigDecimal> result = totalFlowStatisticsService.getMonthsFlowAtYear(salesman, crmUserManagerService.getTurnedShopIds());
            result.forEach((key, value) -> {
                // 判断是否已经有此日的数据了
                BigDecimal b = monthsResult.get(key);
                // 没有则新增
                if (b == null) {
                    monthsResult.put(key, value);
                } else {// 有,则在原基础上增加
                    monthsResult.put(key, b.add(value));
                }
            });
        }

        Map<String, BigDecimal> quartersResult = new LinkedHashMap<>();
        // 所有人
        for (String s : userSet) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s, crmUserManagerService.getTimeRangeList(s));
            Map<String, BigDecimal> result = totalFlowStatisticsService.getQuarterFlowAtYear(salesman, crmUserManagerService.getTurnedShopIds());
            result.forEach((key, value) -> {
                // 判断是否已经有此日的数据了
                BigDecimal b = quartersResult.get(key);
                // 没有则新增
                if (b == null) {
                    quartersResult.put(key, value);
                } else {// 有,则在原基础上增加
                    quartersResult.put(key, b.add(value));
                }
            });
        }

        Map<String, Map<String, BigDecimal>> map = new LinkedHashMap<>();
        map.put("days", daysResult);
        map.put("months", monthsResult);
        map.put("quarters", quartersResult);
        return new ResultObject(200, "success", map);
    }

    /**
     * 获取本月每日统计信息
     *
     * @return 当月每天统计信息
     */
    @RequestMapping(value = "/days", method = RequestMethod.GET)
    public ResultObject getDays(String ids) {
        Set<String> userSet = getSalesmanIdByOrgId(ids);
        Map<String, BigDecimal> totalResult = new HashMap<>();
        // 所有人
        for (String s : userSet) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s, getTimeRangeList(s));
            Map<String, BigDecimal> result = totalFlowStatisticsService.getDaysFlowAtMonth(salesman, crmUserManagerService.getTurnedShopIds());
            result.forEach((key, value) -> {
                // 判断是否已经有此日的数据了
                BigDecimal b = totalResult.get(key);
                // 没有则新增
                if (b == null) {
                    totalResult.put(key, value);
                } else {// 有,则在原基础上增加
                    totalResult.put(key, b.add(value));
                }
            });
        }
        return new ResultObject(200, "success", totalResult);
    }

    /**
     * 获取每个月统计信息
     *
     * @param ids 组织机构列表
     * @return 统计信息
     */
    @RequestMapping(value = "/months", method = RequestMethod.GET)
    public ResultObject getMonths(String ids) {
        Set<String> userSet = getSalesmanIdByOrgId(ids);
        Map<String, BigDecimal> totalResult = new HashMap<>();
        // 所有人
        for (String s : userSet) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s, getTimeRangeList(s));
            Map<String, BigDecimal> result = totalFlowStatisticsService.getMonthsFlowAtYear(salesman, crmUserManagerService.getTurnedShopIds());
            result.forEach((key, value) -> {
                // 判断是否已经有此日的数据了
                BigDecimal b = totalResult.get(key);
                // 没有则新增
                if (b == null) {
                    totalResult.put(key, value);
                } else {// 有,则在原基础上增加
                    totalResult.put(key, b.add(value));
                }
            });
        }
        return new ResultObject(200, "success", totalResult);
    }

    /**
     * 获取今年每个季度的统计信息
     *
     * @param ids 组织机构列表
     * @return 统计信息
     */
    @RequestMapping(value = "/quarters", method = RequestMethod.GET)
    public ResultObject getQuarters(String ids) {
        Set<String> userSet = getSalesmanIdByOrgId(ids);
        Map<String, BigDecimal> totalResult = new HashMap<>();
        // 所有人
        for (String s : userSet) {
            Map<String, List<TimeRange>> salesman = new HashMap<>();
            salesman.put(s, getTimeRangeList(s));
            Map<String, BigDecimal> result = totalFlowStatisticsService.getQuarterFlowAtYear(salesman, crmUserManagerService.getTurnedShopIds());
            result.forEach((key, value) -> {
                // 判断是否已经有此日的数据了
                BigDecimal b = totalResult.get(key);
                // 没有则新增
                if (b == null) {
                    totalResult.put(key, value);
                } else {// 有,则在原基础上增加
                    totalResult.put(key, b.add(value));
                }
            });
        }
        return new ResultObject(200, "success", totalResult);
    }

    /**
     * 查询选中组织机构id下人员列表（不包含子级组织机构）
     *
     * @param ids
     * @return
     */
    public Set<String> getSelfSalemanIdByOrgId(String ids) {
        Set<String> us = new HashSet<>();
        if (StringUtils.isBlank(ids)) {
            //获取当前登录用户所在组织机构的用户关联信息
            UserOrg uo = new UserOrg();
            uo.setUserId(TokenManager.getTokenId());
            List<UserOrg> uolist = userOrgService.selectList(uo);
            Set<String> userSet1 = new HashSet<>();
            for (UserOrg uOrg : uolist) {
                if (TokenManager.getTokenId().equals(uOrg.getUserId())) {
                    userSet1.add(uOrg.getUserId());
                }
            }
            us.addAll(userSet1);
        }
        //查询所有组织机构下的人员
        if (!StringUtils.isBlank(ids)) {
            Set<String> userSet = new HashSet<>();
            for (String s : ids.split(",")) {
                //根据id查询当前组织机构所包含的人员
                UserOrg userOrg = new UserOrg();
                userOrg.setOrgId(s);
                List<UserOrg> userOrgList = userOrgService.selectList(userOrg);
                for (UserOrg org : userOrgList) {
                    userSet.add(org.getUserId());
                }
            }
            us.addAll(userSet);
        }
        return us;
    }

    /**
     * 根据组织机构id,查询本组织机构下的子组织机构销售人员列表(不包含本组织机构的人员)
     *
     * @param ids 组织机构id,多个使用逗号分隔
     * @return 销售人员id列表
     */
    public Set<String> getSalesmanIdByOrgId(String ids) {
        // 查询自身组织机构下的所有组织机构
        UserOrg userOrg = new UserOrg();
        userOrg.setUserId(TokenManager.getTokenId());
        List<UserOrg> userOrgList = userOrgService.selectList(userOrg);
        Set<String> orgIdSet = new HashSet<>();
        for (UserOrg org : userOrgList) {
            orgIdSet.add(org.getOrgId());
        }

        // 如果没有指定,则统计自己组织机构及以下的所有数据
        if (StringUtils.isBlank(ids)) {
            StringBuilder sb = new StringBuilder();
            for (String s : orgIdSet) {
                sb.append(s).append(",");
            }
            if (sb.length() > 0) {
                ids = sb.substring(0, sb.length() - 1);
            }
        }
        // 查询所有组织机构
        List<Organizations> organizationsList = new ArrayList<>();
        for (String s : ids.split(",")) {
            List<Organizations> orgs = organizationsService.selectSubList(s);
            for (Organizations org : orgs) {
                boolean isExist = false;
                for (Organizations organizations : organizationsList) {
                    if (organizations.getId().equals(org.getId())) {
                        isExist = true;
                    }
                }
                if (!isExist) {
                    organizationsList.add(org);
                }
            }
        }
        // 查询所有组织机构下的人员
        Set<String> userSet = new HashSet<>();
        for (Organizations organizations : organizationsList) {
            // 查询所有组织机构关联关系
            UserOrg userOrg2 = new UserOrg();
            userOrg2.setOrgId(organizations.getId());
            List<UserOrg> userOrgList2 = userOrgService.selectList(userOrg2);
            for (UserOrg org : userOrgList2) {
                userSet.add(org.getUserId());
            }
        }
        return userSet;
    }

    /**
     * 获取销售人员有效期时间段列表
     *
     * @param salesmanId 销售人员ID
     * @return 有效时间列表
     */
    public List<TimeRange> getTimeRangeList(String salesmanId) {
        List<TimeRange> timeRangeList = new ArrayList<>();
        UserValidInfo userValidInfo = new UserValidInfo();
        userValidInfo.setUserId(salesmanId);
        List<UserValidInfo> list = userValidInfoService.selectList(userValidInfo);
        // 是否已经开始
        boolean isStarted = false;

        TimeRange timeRange = null;

        // 增加记录
        for (UserValidInfo validInfo : list) {
            if (validInfo.getChangeStatus() == 1) {
                isStarted = true;
            }
            if (isStarted) {
                if (validInfo.getChangeStatus() == 1) {
                    // 防止两次连续设置为有效
                    if (timeRange == null) {
                        timeRange = new TimeRange();
                    }
                    timeRange.setStartTime(validInfo.getChangeTime());
                }
                //增加timeRange判断，防止代码报错，并且防止两次连续设置为null
                if (timeRange != null && validInfo.getChangeStatus() == 0) {
                    timeRange.setEndTime(validInfo.getChangeTime());
                    timeRangeList.add(timeRange);
                    timeRange = null;
                }
            }
        }
        return timeRangeList;
    }
}
